package wang.lx.mybatis.common;

import java.text.ParseException;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.Payload;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;

/**
 * jwt加签 验签
 * 20250708 王的世界
 * https://connect2id.com/products/nimbus-jose-jwt#example
 */
public class JwtUtil {
    public static String SECRET_KEY = "https://connect2id.com/products/nimbus-jose-jwt#example";

    /**
     * 加签
     * @param payloadStr
     * @param secret
     * @return
     * @throws JOSEException
     */
    public static String signWithJwt(String payloadStr,String secret) throws JOSEException {
        JWSObject jwsObject = new JWSObject(new JWSHeader(JWSAlgorithm.HS256),new Payload(payloadStr));
        jwsObject.sign(new MACSigner(secret));
        return jwsObject.serialize();
    }

    /**
     * 验签
     * @param jwttoken
     * @param secret
     * @return
     * @throws ParseException
     * @throws JOSEException
     */
    public static String verifyWithJwt(String jwttoken,String secret) throws ParseException, JOSEException {
        JWSObject jwsObject = JWSObject.parse(jwttoken);
        JWSVerifier verifier = new MACVerifier(secret);
        jwsObject.verify(verifier);
        return jwsObject.getPayload().toString();
    }

}
